package com.example.tiantian.clock;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.example.tiantian.BaseActivity;
import com.example.tiantian.R;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class ClockActivity extends BaseActivity implements OnClickListener, Runnable, OnTimeSetListener {

    TextView txtNow;
    TextView txtDate;
    TextView txtDayOfWeek;
    Button btnSwitch;
    Button btnSetTime;

    Calendar now;
    Calendar alarmTime;

    boolean clockRun;

    SimpleDateFormat sdf;
    boolean alarmIsStart;
    boolean hasPerpare;
    AlarmManager alarmMgr;
    PendingIntent operation;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                setNow();
            }
        }
    };

    @SuppressLint("SimpleDateFormat")

    @Override
    protected void init() {
        setContentView(R.layout.activity_clock);

        txtNow = (TextView) findViewById(R.id.clock_txt_now);
        txtDate = (TextView) findViewById(R.id.clock_txt_date);
        txtDayOfWeek = (TextView) findViewById(R.id.clock_txt_day_of_week);
        btnSwitch = (Button) findViewById(R.id.clock_btn_switch);
        btnSetTime = (Button) findViewById(R.id.clock_btn_set_time);

        alarmTime = Calendar.getInstance();

        now = Calendar.getInstance();

        alarmIsStart = false;
        hasPerpare = false;

        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        sdf = new SimpleDateFormat("yyyy年MM月dd日 E HH:mm:ss");
    }

    @Override
    protected void event() {
        btnSwitch.setOnClickListener(this);
        btnSetTime.setOnClickListener(this);
    }

    @Override
    protected void loadData() {
        clockRun = true;
        new Thread(this).start();
    }

    @Override
    public void run() {
        while (clockRun) {
            now.setTime(new Date());
            handler.sendEmptyMessage(1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.e("TianTian", Thread.currentThread().getName() + ":" + getLocalClassName() + " sleep()", e);
            }
        }
    }

    private void setNow() {
        String[] time = sdf.format(now.getTime()).split(" ");
        txtNow.setText(time[2]);
        txtDate.setText(time[0]);
        txtDayOfWeek.setText(time[1]);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.clock_btn_set_time:
            new TimePickerDialog(this, this, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true).show();
            hasPerpare = true;
            break;
        case R.id.clock_btn_switch:
            alarmClock();
            break;
        default:
            break;
        }
    }

    private void alarmClock() {
        if (!alarmIsStart && hasPerpare) {

            // Intent intent = new Intent(this, AlarmActivity.class);
            // operation = PendingIntent.getActivity(this, 100, intent,
            // PendingIntent.FLAG_UPDATE_CURRENT);

            // Intent intent = new Intent(this, AlarmReceiver.class);
            // operation = PendingIntent.getBroadcast(this, 100, intent,
            // PendingIntent.FLAG_CANCEL_CURRENT);

            Intent intent = new Intent(this, AlarmService.class);
            operation = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            intent.putExtra("alarmTime", alarmTime.getTimeInMillis());

            alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), operation);
            toast("启动闹钟" + sdf.format(alarmTime.getTime()));
            btnSwitch.setText(R.string.clock_btn_switch_off);
            alarmIsStart = true;

        } else {
            if (operation != null) {
                alarmMgr.cancel(operation);
            }
            if (hasPerpare) {
                toast("关闭闹钟");
            } else {
                toast("请先设定闹钟时间");
            }
            clear();
            hasPerpare = false;
        }
    }

    private void clear() {
        btnSwitch.setText(R.string.clock_btn_switch_on);
        btnSetTime.setText(R.string.clock_btn_set_time);
        alarmIsStart = false;
        hasPerpare = false;
        alarmTime.setTime(new Date());
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        clear();

        alarmTime.add(Calendar.SECOND, -alarmTime.get(Calendar.SECOND));
        alarmTime.add(Calendar.MILLISECOND, -alarmTime.get(Calendar.MILLISECOND));

        addTime(hourOfDay, minute);
        btnSetTime.setText((hourOfDay >= 10 ? "" : "0") + hourOfDay + ":" + (minute >= 10 ? "" : "0") + minute);

    }

    private void addTime(int hourOfDay, int minute) {
        int nowMin = now.get(Calendar.MINUTE);
        int nowHour = now.get(Calendar.HOUR_OF_DAY);
        int hourAdd = hourOfDay - nowHour;
        int minAdd = minute - nowMin;
        hourAdd = hourAdd < 0 ? 24 - hourAdd : ((minAdd > 0) ? hourAdd : 24 - hourAdd);
        alarmTime.add(Calendar.HOUR, hourAdd);
        alarmTime.add(Calendar.MINUTE, minAdd);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clockRun = false;
    }

}
